package com.gzx.spring.apis.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzx.risk.core.apis.context.ApiContext;
import com.gzx.risk.core.apis.result.RiskResult;
import com.gzx.risk.core.apis.result.xiaoniu.XiaoniuR201;
import com.gzx.risk.core.apis.result.xiaoniu.XiaoniuR301;
import com.gzx.spring.apis.utils.XiaoniuUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class XiaoniuService {
	@Value("${apis.xiaoniu.appId}")
	private String appId;
	@Value("${apis.xiaoniu.appSecret}")
	private String appSecret;
	@Value("${apis.xiaoniu.apiUrl}")
	private String apiUrl;
	@Value("${apis.xiaoniu.env}")
	private String env;

	private final ObjectMapper objectMapper;

	public XiaoniuService(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	public String r301(String name, String id, String phone) throws Exception {
		XiaoniuUtil util = new XiaoniuUtil().appId(appId).apiUrl(apiUrl).appSecret(appSecret);
		return util.r301(name, id, phone);
	}

	public String r201(String name, String id, String phone) throws Exception {
		XiaoniuUtil util = new XiaoniuUtil().appId(appId).apiUrl(apiUrl).appSecret(appSecret);
		return util.r201(name, id, phone);
	}

	public RiskResult r301(String groupName, ApiContext ctx) throws Exception {
		String apiName = "xiaoniu_r301";
		String json = "";
		if ("debug".equals(env)) {
			json = ApiExec.loadJson("/debug/xiaoniu/r301");
		} else {
			json = this.r301(ctx.getUserInfo().getName(), ctx.getUserInfo().getId(), ctx.getUserInfo().getPhone());
			log.debug("{}:{}", apiName, json);
		}
		XiaoniuR301 obj = objectMapper.readValue(json, XiaoniuR301.class);
		obj.setGroupName(groupName);
		obj.setDataName(apiName);
		if (obj.getCode() == 0 && obj.getHit() == 1) {
			ctx.add(obj);
		} else {
			log.warn("{},code:{},msg:{}", apiName, obj.getCode(), obj.getMsg());
		}
		return obj;
	}
 
	public RiskResult r201(String groupName, ApiContext ctx) throws Exception {
		String apiName = "xiaoniu_r201";
		String json = "";
		if ("debug".equals(env)) {
			json = ApiExec.loadJson("/debug/xiaoniu/r201");
		} else {
			json = this.r201(ctx.getUserInfo().getName(), ctx.getUserInfo().getId(), ctx.getUserInfo().getPhone());
			log.debug("{}:{}", apiName, json);
		}
		XiaoniuR201 obj = objectMapper.readValue(json, XiaoniuR201.class);
		obj.setGroupName(groupName);
		obj.setDataName(apiName);
		if (obj.getCode() == 0 && obj.getHit() == 1) {
			ctx.add(obj);
		} else {
			log.warn("{},code:{},msg:{}", apiName, obj.getCode(), obj.getMsg());
		}
		return obj;
	}
}
